/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/* 
 * key var,login state
 */
var isLogin = false;//在首页jsp文件中定义
var userId = -1;


var userCount = 0;
function showUserInfo(userId,userName)
{
    var mgr = new Ext.Updater("divUserInfo1");
    mgr.update({
        url: "user/viewUserData.jsp", 
            params: "userId="+userId,
            text: "正在加载用户数据..."
        });
    userCount++;
    mgr.on("update", function(){
            panel.add({
                id:'user'+userCount,
                html:document.getElementById('divUserInfo1').innerHTML,
                title:"用户:"+userName,
                closable:true,
                autoScroll:true
            });
            panel.activate('user'+userCount);
        });
}

function logout()
{
    var answer = Ext.MessageBox.show({
        title: '提示',
        msg: '您确定要退出吗？',
        width:200,
        icon: Ext.MessageBox.QUESTION,
        buttons: Ext.MessageBox.OKCANCEL,
        fn :function(btn, text){
            if (btn != 'ok'){
                return
            }
            else
            {
                //执行服务器退出操作
                var logoutUpdater = new Ext.Updater("divLogout");
                logoutUpdater.update({
                    url: "../UserController",
                    params: "action=logout&redirect=no",
                    text: "正在退出..."
                });

                logoutUpdater.on("update", function(){window.setTimeout(LoadRecentTopics,1000);window.setTimeout(RefreshUserInfo,1000);window.setTimeout(LoadFriends,1000);window.setTimeout(RefreshToolBar,300);});
                isLogin = false;
                userId = -1;
            }
        }
    });
}

var winSimpleView;
function showSimpleViewOfUser(userId)
{
    if(winSimpleView==null){
        winSimpleView = new Ext.Tip({
          //el:'divSimpleViewFrame',
          //layout:'fit',
          //title:'<center>用户信息</center>',
          width:200,
          //height:370,
          resizable:false,
          autoScroll :true,
          closeAction:'hide',
          closable :false,
          autoHeight:true,
          //autoWidth:true,
          border :false,
          items: [divSimpleView]
      });
    }
    Ext.get("divSimpleView").load({
        url: "user/SimpleView.jsp",
        //scripts: true,
        params: "userId="+userId,
        text: "正在加载数据..."
    });
    winSimpleView.show();
    winSimpleView.setPosition(window.event.clientX>800?window.event.clientX-230:window.event.clientX+5,window.event.clientY>480?window.event.clientY-127:window.event.clientY+5);
}
function hideSimpleViewOfUser()
{
    winSimpleView.hide();
}

var upLoadDlg;
function BeginUploadHead()
{
    if(upLoadDlg == null)
    {
        upLoadDlg = new Ext.Window(
        {
            el:'upFile-dlg',
            width:370,
            height:100,
            modal:true,
            closeAction:'hide',
            resizable: false,
            plain: true,
            buttons: [
            {
                text: "上传",
                handler: uploadfile
            },{
                text: '取消',
                handler: function(){
                    upLoadDlg.hide();
                }
            }]
        });
    }
    upLoadDlg.show(Ext.get('userInfoBtn').dom);

    function uploadfile()
    {
        var uploadForm = new Ext.form.BasicForm('headFileForm',{});
        
        var fileUp = new Ext.form.TextField( {
            applyTo:'fileUp',
            id : 'fileUp',
            allowBlank : false,
            width : 340
        });
        uploadForm.add(fileUp);
        //var fileValue = Ext.get('headUploadText').dom.value;
        if(uploadForm.isValid())
        {
            upLoadDlg.hide();
            uploadForm.doAction('submit', { 
                url : "user/acceptFile.jsp", 
                method : 'post',
                //提交成功的回调函数
                success:function(form,action){
                    TipMessageShow('提示',"头像上传成功");
                },
                //提交失败的回调函数
                failure:function(){
                    Ext.Msg.alert('错误','连接服务器失败！');
                }
            });
        }else
        {
            Ext.MessageBox.alert("提示","请选择需要上传的文件!");
        }
    }
    //RefreshUserInfo();
}
function showTempHeadImg(src)
{
    //document.getElementById('tempHead').src=src;
}


var headUpdater;
var winChangeHead;
function BeginChangeHead()
{
    if(headUpdater==null)
        headUpdater = new Ext.Updater("divChangeHead");
    if(winChangeHead==null)
    {        
        winChangeHead=new Ext.Window({       
            labelAlign: 'center',      
            title: '更换头像',       
            bodyStyle:'padding:5px 5px 0',       
            width: 370,
            items: [             
                {                 
                    layout:'column',              
                    items:[            
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default1.jpg" width="80" height="80" alt="default"/>',checked :true,name:'headSelect',
                                    id:'headSelect1'})
                            ]                     
                        },                    
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default2.jpg" width="80" height="80" alt="default"/>', id:'headSelect2',name:'headSelect'}
                            )]
                        },                    
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default3.jpg" width="80" height="80" alt="default"/>', id:'headSelect3',name:'headSelect'}
                            )]
                        },                    
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default4.jpg" width="80" height="80" alt="default"/>', id:'headSelect4',name:'headSelect'}
                            )]
                        }
                    ]
                },
                {                 
                    layout:'column',              
                    items:[            
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default5.jpg" width="80" height="80" alt="default"/>', 
                                    id:'headSelect5',name:'headSelect'})
                            ]                     
                        },                    
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default6.jpg" width="80" height="80" alt="default"/>', id:'headSelect6',name:'headSelect'}
                            )]
                        },                    
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default7.jpg" width="80" height="80" alt="default"/>', id:'headSelect7',name:'headSelect'}
                            )]
                        },                    
                        {items: [
                                new Ext.form.Radio({
                                    boxLabel:'<img src="../images/heads/default8.jpg" width="80" height="80" alt="default"/>', id:'headSelect8',name:'headSelect'}
                            )]
                        }
                    ]
                }
            ],
            buttons: [
            {
                text: "上传",
                handler: changeHead
            },{
                text: '取消',
                handler: function(){
                    winChangeHead.hide();
                }
            }]
        });

        function changeHead()
        {
            var answer = Ext.MessageBox.show({
                title: '提示',
                msg: '您确定要选择此头像吗？',
                width:200,
                icon: Ext.MessageBox.QUESTION,
                buttons: Ext.MessageBox.OKCANCEL,
                fn :function(btn, text){
                    if (btn != 'ok'){
                        return
                    }
                    else
                    {
                        var i = 1;
                        for(;i<=8;i++)
                        {
                            if(document.getElementById('headSelect'+i).checked)
                            {
                                break;
                            }
                        }
                        //开始提交新头像
                        var conn = new Ext.data.Connection();
                          // 发送异步请求
                        conn.request({
                          // 请求地址
                            url: '../UserController',
                            method: 'GET',
                            params:'action=changehead&headSelect='+i,
                            // 指定回调函数
                            callback: callback
                        });
                        //回调函数
                        function callback(options, success, response){
                            if(success&&(response.responseText=='修改成功')){
                              // 如果成功则使用Ext将JSON字符串转换为JavaScript对象
                              //var jsonObj = Ext.util.JSON.decode(response.responseText);
                                winChangeHead.hide();
                                TipMessageShow('消息提示','头像修改成功');
                                RefreshUserInfo();
                            }
                            else if(success)
                            {
                                Ext.Msg.alert('错误提示',response.responseText);
                            }
                            else
                            {
                                Ext.Msg.alert('错误提示','连接服务器失败，请重试');
                            }
                        }
                    }
                }
            });
        }
    }
    winChangeHead.show(Ext.get('userInfoBtn').dom);
  /*/  headUpdater.update({
        url: "user/heads.jsp", 
        text: "正在加载用户数据..."
    });
    headUpdater.on("update", function(){
        winChangeHead.show(Ext.get('userInfoBtn').dom);
    }); */
}

function RefreshUserInfo()
{
    Ext.get("userinfo").load({
        url: "user/userInfoData.jsp",
        scripts: true,
        params: "todo=refresh",
        text: "正在更新个人信息..."
    });

}
function LoadRecentTopics()
{
    Ext.get("rectopics").load({
        url: "user/recentTopicsData.jsp",
        scripts: true,
        text: "正在帖子列表..."
    });

}

function RefreshToolBar()
{
    var tempCon = Ext.get("loginBtn");
    if(isLogin)
    {
        if(tempCon!=null)
            Ext.get("loginBtn").hide();//tb.removeButton(1);//
        //tb.render(toolsbar);
    }
    tb.destroy();
    TemplateToolbar();
}

function LoadFriends()
{
    Ext.get("friends").load({
        url: "user/friends.jsp",
        scripts: true,
        text: "正在读取好友信息..."
    });
}

var winFriendPanel;
function showFriendPanel(userId)
{//alert('gg');
    if(winFriendPanel==null){
        winFriendPanel = new Ext.Tip({
          //el:'divSimpleViewFrame',
          //layout:'fit',
          //title:'<center>用户信息</center>',
          width:80,
          //height:470,
          resizable:false,
          autoScroll :true,
          closeAction:'hide',
          closable :true,
          autoHeight:true,
          //autoWidth:true,
          border :false,
          items: [divFriendPanel]
      });
    }
    Ext.get("divFriendPanel").load({
        url: "user/friends.jsp",
        //scripts: true,
        params: "todo=control&userId="+userId,
        text: "正在加载数据..."
    });
    mouseCount = 0;
    winFriendPanel.show();
    winFriendPanel.setPosition(window.event.clientX>800?window.event.clientX-230:window.event.clientX+5,window.event.clientY>480?window.event.clientY-127:window.event.clientY+5);
}
var mouseCount = 0;
function HideTip()
{
    mouseCount++;//alert(mouseCount=0);
    if(mouseCount==2)
    {
        if(winFriendPanel!=null)
        {
            winFriendPanel.hide();
            mouseCount=0
        }
    }
}

function goLogin(){	
            //使用表单提示
            Ext.QuickTips.init();
            Ext.form.Field.prototype.msgTarget = 'side';
    
            //定义表单
            var simple = new Ext.FormPanel({
                labelWidth: 55, 			
                baseCls: 'x-plain',
                modal:true,
                defaults: {width: 150,bodyStyle:'padding:18px'},
                defaultType: 'textfield',//默认字段类型
                labelAlign :'right',
                //定义表单元素
                items: [{
                        fieldLabel: '用户名',
                        name: 'name',//元素名称
                        //anchor:'95%',//也可用此定义自适应宽度
                        allowBlank:false,//不允许为空
                        blankText:'用户名不能为空'//错误提示内容
                    },{
                        inputType:'password',
                        fieldLabel: '密码',
                        //anchor:'95%',
                        name: 'password',
                        allowBlank:false,
                        blankText:'密码不能为空'
                    },{
                        name: 'validateCode',
                        fieldLabel: '验证码',
                        maxLength: 4,
                        width: 120,
                        style: 'font-size:14px;font-weight:bold;letter-spacing: 1px; background:url(checkCode.jsp?width=75&heigth=20); background-repeat: no-repeat; background-position: 40px 1px;center right no-repeat;',  // alidateCode.jsp 是产生验证码的图片的JSP页面
                        allowBlank:false,
                        blankText:'验证码不能为空!'
                    }
                ]
            });
            var isSuccess = false;
            winxx = new Ext.Window({
                //id:'win',
                title:'用户登陆',
                layout:'fit',	//之前提到的布局方式fit，自适应布局					
                width:250,
                height:192,
                plain:true,
                bodyStyle:'padding:5px;',
                maximizable:false,//禁止最大化
                closeAction:'close',
                closable:true,//禁止关闭
                collapsible:true,//可折叠
                modal: true,
                //buttonAlign:'center',
                items:simple,//将表单作为窗体元素嵌套布局
                buttons: [{
                        text: '登陆',
                        type: 'submit',
                        //定义表单提交事件
                        handler:function(){
                            if(simple.form.isValid()){//验证合法后使用加载进度条
                                var xxx = Ext.MessageBox.show({
                                    id:'loginProcess',
                                    title: '请稍等',
                                    msg: '正在登录...',
                                    progressText: '',
                                    width:300,
                                    progress:true,
                                    closable:true,
                                    animEl: 'loding'
                                });
                                //控制进度速度
                                var f = function(v){
                                    return function(){
                                        var i = v/10;
                                        Ext.MessageBox.updateProgress(i, '正在登录');
                                        if(v==10&&!isSuccess)
                                        {
                                            Ext.Msg.alert('提示','对不起，连接服务器失败，请重新尝试');
                                            winxx.hide();
                                            //xxx.hide();
                                        }
                                    };
                                };
    
                                for(var i = 1; i < 11; i++){
                                    setTimeout(f(i), i*200);
                                }
                                //xxx.hide();
                                //提交到服务器操作
                                simple.form.doAction('submit',{
                                    url:'user/CheckUser.jsp',//文件路径
                                    method:'post',//提交方法post或get
                                    params:'',
                                    //提交成功的回调函数
                                    success:function(form,action){
                                        isSuccess = true;
                                        winxx.hide();
                                        xxx.hide();
                                        isLogin=true;
                                        //userId的值如何获得？
                                        RefreshUserInfo();
                                        LoadRecentTopics();
                                        RefreshToolBar();
                                        LoadFriends();
                                    },
                                    //提交失败的回调函数
                                    failure:function(){
                                        isSuccess = true;
                                        Ext.Msg.alert('错误','用户名与密码不匹配！');
                                    }
                                });
                            }                               						   
                        }
                    },{
                        text: '取消',
                        handler:function(){winxx.hide();}//simple.form.reset();}//重置表单
                    }]
            });
            winxx.show(Ext.get('loginBtn').dom);//显示窗体
}

function login()
{
    var isConnectSuccess = false;
    var xxx = Ext.MessageBox.show({
        id:'loginProcess',
        title: '请稍等',
        msg: '正在登录...',
        progressText: '',
        width:300,
        progress:true,
        closable:true,
        animEl: 'loding'
    });
    //控制进度速度
    var f = function(v){
        return function(){
            var i = v/10;
            Ext.MessageBox.updateProgress(i, '正在登录');
            if(v==10&&!isConnectSuccess)
            {
                //Ext.Msg.alert('提示','对不起，连接服务器超时，请重新尝试');
                winLogin.hide();
                isShowingMsg = false;//重新设置消息提示框的状态为假
            }
        };
    };

    for(var i = 1; i < 11; i++){
        setTimeout(f(i), i*200);
    }
    var conn = new Ext.data.Connection();
      // 发送异步请求
    conn.request({
      // 请求地址
        url: '../UserController',
        method: 'GET',
        params:'action=login&username='+document.getElementById('divLoginInfo').getElementsByTagName('input')[0].value+'&password='+document.getElementById('divLoginInfo').getElementsByTagName('input')[1].value+'&checkcode='+document.getElementById('divLoginInfo').getElementsByTagName('input')[2].value,
        // 指定回调函数
        callback: callback
    });
    //回调函数
    function callback(options, success, response){
        if(success&&(response.responseText=='登录成功')){
          // 如果成功则使用Ext将JSON字符串转换为JavaScript对象
          //var jsonObj = Ext.util.JSON.decode(response.responseText);
            isConnectSuccess = true;
            winLogin.hide();
            xxx.hide();
            isLogin=true;
            //userId的值如何获得？
            RefreshUserInfo();
            LoadRecentTopics();
            RefreshToolBar();
            LoadFriends();
            TipMessageShow('消息提示','登录成功');
            setTimeout(checkMessage,msgTimeOut);
        }
        else if(success)
        {
            isConnectSuccess = true;
            Ext.Msg.alert('错误提示',response.responseText);
            refreshCode();
        }
        else
        {
            Ext.Msg.alert('错误提示','连接服务器失败，请重试');
            refreshCode();
        }
    }
}

function register()
{
    if(!checkRegInput())
        return;
    var conn = new Ext.data.Connection();
      // 发送异步请求
    conn.request({
      // 请求地址
        url: '../UserController',
        method: 'GET',
        params:'action=register&username='+document.getElementById('divRegInfo').getElementsByTagName('input')[0].value+'&password='+document.getElementById('divRegInfo').getElementsByTagName('input')[1].value+'&checkcode='+document.getElementById('divRegInfo').getElementsByTagName('input')[3].value,
        // 指定回调函数
        callback: callback
    });
    //回调函数
    function callback(options, success, response){
        if(success&&(response.responseText=='注册成功')){
          // 如果成功则使用Ext将JSON字符串转换为JavaScript对象
          //var jsonObj = Ext.util.JSON.decode(response.responseText);
            TipMessageShow('消息提示','注册成功');
            winReg.hide();
            isLogin=true;
            //userId的值如何获得？
            RefreshUserInfo();
            LoadRecentTopics();
            RefreshToolBar();
            LoadFriends();
        }
        else if(success)
        {
            Ext.Msg.alert('错误提示',response.responseText);
        }
        else
        {
            Ext.Msg.alert('错误提示','连接服务器失败，请重试');
        }
    }
}

var winPersonal;
var toShowPersonal = true;
function showPerson()
{
    if(winPersonal==null){
        winPersonal = new Ext.Tip({
          //el:'divSimpleViewFrame',
          //layout:'fit',
          //title:'<center>用户信息</center>',
          width:92,
          height:100,
          resizable:false,
          closeAction:'hide',
          closable :false,
          border :false,
          items: [divPersonal]
      });
      
      Ext.get("divPersonal").load({
          url: "user/SimpleView.jsp",
          //scripts: true,
          params: "todo=personal",
          text: "正在加载数据..."
      });
    }
    if(toShowPersonal)
    {
        winPersonal.show();
        winPersonal.setPosition(screen.availWidth-96,2);
        toShowPersonal = false;
    }
    else
    {
        winPersonal.hide();
        toShowPersonal = true;
    }
}

var winChangePsw ;
    //Ext.onReady(createRegWin);
function beginChangePsw(){
    if(winChangePsw ==null)
    {
        winChangePsw  = new Ext.Window({
            //el:'divRegFrame',
            layout:'fit',
            modal:true,
            title:'<center>修改密码</center>',
            width:300,
            height:163,
            resizable:false,
            closeAction:'hide',
            items: [divChPswInfo],
            buttons: [{
                text:'确定注册',
                handler: changePsw
            }]
        });
    }
    winChangePsw.show(Ext.get('userInfoBtn').dom);
}
function changePsw()
{
    if(document.getElementById('divChPswInfo').getElementsByTagName('input')[1].value.length<6)
    {
        Ext.Msg.alert('提示','密码不能少于6位');
        return;
    }
    if(document.getElementById('divChPswInfo').getElementsByTagName('input')[1].value!=document.getElementById('divChPswInfo').getElementsByTagName('input')[2].value)
    {
        Ext.Msg.alert('提示','两次输入的密码不一致');
        return;
    }
    //开始提交新密码
    var conn = new Ext.data.Connection();
      // 发送异步请求
    conn.request({
      // 请求地址
        url: '../UserController',
        method: 'GET',
        params:'action=changepsw&password='+document.getElementById('divChPswInfo').getElementsByTagName('input')[0].value+'&newpsw='+document.getElementById('divChPswInfo').getElementsByTagName('input')[1].value,
        // 指定回调函数
        callback: callback
    });
    //回调函数
    function callback(options, success, response){
        if(success&&(response.responseText=='密码修改成功')){
          // 如果成功则使用Ext将JSON字符串转换为JavaScript对象
          //var jsonObj = Ext.util.JSON.decode(response.responseText);
            TipMessageShow('消息提示','密码修改成功，请保管好您的密码');
            winChangePsw.hide();
        }
        else if(success)
        {
            Ext.Msg.alert('错误提示',response.responseText);
        }
        else
        {
            Ext.Msg.alert('错误提示','连接服务器失败，请重试');
        }
    }
}

var winChangeNick ;
    //Ext.onReady(createRegWin);
function BeginChangeNick(){
    if(winChangeNick ==null)
    {
        winChangeNick  = new Ext.Window({
            //el:'divRegFrame',
            layout:'fit',
            modal:true,
            title:'<center>输入新的昵称</center>',
            width:260,
            height:115,
            resizable:false,
            closeAction:'hide',
            items: [divChNickName],
            buttons: [{
                text:'确定修改',
                handler: ChangeNick
            }]
        });
    }
    winChangeNick.show(Ext.get('userInfoBtn').dom);
}
function ChangeNick()
{
    if(document.getElementById('divChNickName').getElementsByTagName('input')[0].value.length<1)
    {
        Ext.Msg.alert('提示','请输入新的昵称');
        return;
    }
    //开始提交新昵称
    var conn = new Ext.data.Connection();
      // 发送异步请求
    conn.request({
      // 请求地址
        url: '../UserController',
        method: 'POST',
        params:'action=changenick&nickname='+document.getElementById('divChNickName').getElementsByTagName('input')[0].value,
        // 指定回调函数
        callback: callback
    });
    //回调函数
    function callback(options, success, response){
        if(success&&(response.responseText=='修改成功')){
            // 如果成功则使用Ext将JSON字符串转换为JavaScript对象
            //var jsonObj = Ext.util.JSON.decode(response.responseText);
            TipMessageShow('消息提示','昵称修改成功');
            RefreshUserInfo();
            winChangeNick.hide();
        }
        else if(success)
        {
            Ext.Msg.alert('错误提示',response.responseText);
        }
        else
        {
            Ext.Msg.alert('错误提示','连接服务器失败，请重试');
        }
    }
}